﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;


namespace Apex.ASPNETCore.GlobalException
{
    /// <summary>
    /// 全局用户异常处理：元素溢出、rabbitMQ连接失败、除数不能为0等
    /// </summary>
    public class GlobalExceptionFilter : IAsyncExceptionFilter
    {
        public Task OnExceptionAsync(ExceptionContext context)
        {
            // 捕获异常并修改返回值(精简报错信息)
            //context.HttpContext.Response.Clear();
            var serialzeStr = CreateErrorResponseHelper.CreateErrorResponse(500,$"Message:{context.Exception.Message}\nStackTrace:{context.Exception.StackTrace}").ToJsonString();
            context.Result = new ObjectResult(serialzeStr)
            {
                StatusCode = 500
            };
            context.ExceptionHandled = true; // 表示异常已经处理
            return Task.CompletedTask;
        }
    }
}
